package com.awanp3.nimbus.demo.service.impl;

import cn.hutool.core.date.DateUtil;
import com.awanp3.nimbus.demo.domain.DemoLeave;
import com.awanp3.nimbus.demo.domain.bo.DemoLeaveBo;
import com.awanp3.nimbus.demo.domain.vo.DemoLeaveVo;
import com.awanp3.nimbus.demo.mapper.DemoLeaveMapper;
import com.awanp3.nimbus.demo.service.IDemoLeaveService;
import com.awanp3.nimbus.workflow.api.RemoteWorkflowService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.awanp3.nimbus.common.core.enums.BusinessStatusEnum;
import com.awanp3.nimbus.common.core.utils.MapstructUtils;
import com.awanp3.nimbus.common.core.utils.StringUtils;
import com.awanp3.nimbus.common.mybatis.core.domain.BaseEntity;
import com.awanp3.nimbus.common.mybatis.core.page.PageQuery;
import com.awanp3.nimbus.common.mybatis.core.page.TableDataInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 请假Service业务层处理
 *
 * @author nimbus
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class DemoLeaveServiceImpl implements IDemoLeaveService {

    private final DemoLeaveMapper baseMapper;

    @DubboReference
    private RemoteWorkflowService remoteWorkflowService;

    /**
     * spel条件表达：判断小于2
     *
     * @param leaveDays 待判断的变量（可不传自行返回true或false）
     * @return boolean
     */
    public boolean eval(Integer leaveDays) {
        if (leaveDays < 2) {
            return true;
        }
        return false;
    }

    /**
     * 查询请假
     */
    @Override
    public DemoLeaveVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询请假列表
     */
    @Override
    public TableDataInfo<DemoLeaveVo> queryPageList(DemoLeaveBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DemoLeave> lqw = buildQueryWrapper(bo);
        Page<DemoLeaveVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询请假列表
     */
    @Override
    public List<DemoLeaveVo> queryList(DemoLeaveBo bo) {
        LambdaQueryWrapper<DemoLeave> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DemoLeave> buildQueryWrapper(DemoLeaveBo bo) {
        LambdaQueryWrapper<DemoLeave> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLeaveType()), DemoLeave::getLeaveType, bo.getLeaveType());
        lqw.ge(bo.getStartLeaveDays() != null, DemoLeave::getLeaveDays, bo.getStartLeaveDays());
        lqw.le(bo.getEndLeaveDays() != null, DemoLeave::getLeaveDays, bo.getEndLeaveDays());
        lqw.orderByDesc(BaseEntity::getCreateTime);
        return lqw;
    }

    /**
     * 新增请假
     */
    @Override
    public DemoLeaveVo insertByBo(DemoLeaveBo bo) {
        long day = DateUtil.betweenDay(bo.getStartDate(), bo.getEndDate(), true);
        // 截止日期也算一天
        bo.setLeaveDays((int) day + 1);
        DemoLeave add = MapstructUtils.convert(bo, DemoLeave.class);
        if (StringUtils.isBlank(add.getStatus())) {
            add.setStatus(BusinessStatusEnum.DRAFT.getStatus());
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return MapstructUtils.convert(add, DemoLeaveVo.class);
    }

    /**
     * 修改请假
     */
    @Override
    public DemoLeaveVo updateByBo(DemoLeaveBo bo) {
        DemoLeave update = MapstructUtils.convert(bo, DemoLeave.class);
        baseMapper.updateById(update);
        return MapstructUtils.convert(update, DemoLeaveVo.class);
    }

    /**
     * 批量删除请假
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(List<Long> ids) {
        remoteWorkflowService.deleteInstance(ids);
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 总体流程监听(例如: 草稿，撤销，退回，作废，终止，已完成，单任务完成等)
     * 正常使用只需#processEvent.flowCode=='leave1'
     * 示例为了方便则使用startsWith匹配了全部示例key
     *
     * @param processEvent 参数
     */
//    @EventListener(condition = "#processEvent.flowCode.startsWith('leave')")
//    public void processHandler(ProcessEvent processEvent) {
//        TenantHelper.dynamic(processEvent.getTenantId(), () -> {
//            log.info("当前任务执行了{}", processEvent.toString());
//            DemoLeave DemoLeave = baseMapper.selectById(Convert.toLong(processEvent.getBusinessId()));
//            DemoLeave.setStatus(processEvent.getStatus());
//            // 用于例如审批附件 审批意见等 存储到业务表内 自行根据业务实现存储流程
//            Map<String, Object> params = processEvent.getParams();
//            if (MapUtil.isNotEmpty(params)) {
//                // 历史任务扩展(通常为附件)
//                String hisTaskExt = Convert.toStr(params.get("hisTaskExt"));
//                // 办理人
//                String handler = Convert.toStr(params.get("handler"));
//                // 办理意见
//                String message = Convert.toStr(params.get("message"));
//            }
//            if (processEvent.getSubmit()) {
//                DemoLeave.setStatus(BusinessStatusEnum.WAITING.getStatus());
//            }
//            baseMapper.updateById(DemoLeave);
//        });
//    }

    /**
     * 执行任务创建监听
     * 示例：也可通过  @EventListener(condition = "#processTaskEvent.flowCode=='leave1'")进行判断
     * 在方法中判断流程节点key
     * if ("xxx".equals(processTaskEvent.getNodeCode())) {
     * //执行业务逻辑
     * }
     *
     * @param processTaskEvent 参数
     */
//    @EventListener(condition = "#processTaskEvent.flowCode.startsWith('leave')")
//    public void processTaskHandler(ProcessTaskEvent processTaskEvent) {
//        log.info("当前任务创建了{}", processTaskEvent.toString());
//    }

    /**
     * 监听删除流程事件
     * 正常使用只需#processDeleteEvent.flowCode=='leave1'
     * 示例为了方便则使用startsWith匹配了全部示例key
     *
     * @param processDeleteEvent 参数
     */
//    @EventListener(condition = "#processDeleteEvent.flowCode.startsWith('leave')")
//    public void processDeleteHandler(ProcessDeleteEvent processDeleteEvent) {
//        TenantHelper.dynamic(processDeleteEvent.getTenantId(), () -> {
//            log.info("监听删除流程事件，当前任务执行了{}", processDeleteEvent.toString());
//            DemoLeave DemoLeave = baseMapper.selectById(Long.valueOf(processDeleteEvent.getBusinessId()));
//            if (ObjectUtil.isNull(DemoLeave)) {
//                return;
//            }
//            baseMapper.deleteById(DemoLeave.getId());
//        });
//    }

}
